package org.practice.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
	public static final int MAX_AGE = 60 * 60 * 24 * 7;

	public static final String USER_ID = "dangshop.user.id";
	
	public static final String PATH = "/dang-shop1.0";

	/**
	 * 
	 * @param response
	 * @param key
	 * @param value
	 * @throws UnsupportedEncodingException
	 */
	public static void addCookie(HttpServletResponse response, String key,
			String value) throws UnsupportedEncodingException {
		addCookie(response, key, value, MAX_AGE);
	}

	public static void deleteCookie(HttpServletResponse response, String key) {
		Cookie cookie = new Cookie(key, "");
		cookie.setMaxAge(0);
		cookie.setPath(PATH);
		response.addCookie(cookie);
	}

	/**
	 * cookieValue,expires=Tue, 30 Oct 2012 12:56:48 GMT; path=/dang-shop1.0; domain=localhost
	 * @param response
	 * @param key
	 * @param value
	 * @param maxAge
	 * @throws UnsupportedEncodingException
	 */
	public static void addCookie(HttpServletResponse response, String key,
			String value, int maxAge) throws UnsupportedEncodingException {
		value = URLEncoder.encode(value, "utf-8");
		Cookie cookie = new Cookie(key, value);
		cookie.setMaxAge(maxAge);
		cookie.setPath(PATH);
		response.addCookie(cookie);
	}

	/**
	 * 
	 * @param request
	 * @param key
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String findCookie(HttpServletRequest request, String key)
			throws UnsupportedEncodingException {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				if (key.equals(cookies[i].getName())) {
					return URLDecoder.decode(cookies[i].getValue(), "utf-8");
				}
			}
		}
		return null;
	}
}
